package com.chlp.core.framework.controller;

import com.chlp.core.framework.service.CommonCurdService;
import com.chlp.core.framework.utils.CommonCurdResultBean;
import com.chlp.core.framework.utils.CommonSingleTableCurdBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

/**
 * @author 陈礼鹏
 * @date 2020/1/16 17:23
 */
@Api(tags = " 通用CRUD", value = "通用CRUD")
@RequestMapping("/singleTable")
@ResponseBody
@RestController
public class SingleTableCurdController {

    private final static String INSERT = "insert";
    private final static String DELETE = "delete";
    private final static String UPDATE = "update";
    private final static String SELECT = "select";
    private final CommonCurdService commonCurdService;

    public SingleTableCurdController(CommonCurdService commonCurdService) {
        this.commonCurdService = commonCurdService;
    }

    @ApiOperation(value = "单表通用CURD接口")
    @PostMapping(value = "/crud")
    public CommonCurdResultBean<Object> crud(@RequestBody CommonSingleTableCurdBean curdBean) {
        CommonCurdResultBean<Object> resultBean = new CommonCurdResultBean<>(true, "");

        String type = curdBean.getType();
        String entity = curdBean.getEntity();
        Object entityValue = curdBean.getEntityValue();
        try {
            Class t = Class.forName(entity);
            ObjectMapper objectMapper = new ObjectMapper();
            Object value = objectMapper.convertValue(entityValue, t);
            switch (type) {
                case INSERT:
                    resultBean.setObject(commonCurdService.insertOne(value));
                    break;
                case DELETE:
                    commonCurdService.deleteByEntity(value);
                    break;
                case UPDATE:
                    commonCurdService.updateById(value);
                    break;
                case SELECT:
                    resultBean.setObject(commonCurdService.queryAnyTableByConditionPage(value, 0, 0));
                    break;
                default:
                    throw new IllegalStateException("Unexpected value: " + type);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return resultBean;
    }
}